# Who Will Defend Democracy? Evaluating Tradeoffs in Candidate Support Among Partisan Donors and Voters
# Step 3: Calculate and plot AMCEs
# Last updated: June 19, 2020

# Initial settings --------------------------------------------------------

library(tidyverse)
library(cjoint)
library(ggthemes)

# Load relevant functions -------------------------------------------------

source("functions/specify_parameters.R")
source("functions/estimate_AMCEs.R")
source("functions/compare_AMCEs.R")
source("functions/order_attributes_levels.R")
source("functions/set_my_ggtheme.R")
source("functions/plot_AMCEs.R")
source("functions/specify_color_palette.R")
source("functions/plot_AMCEs_comparison.R")
source("functions/set_my_ggtheme_legend.R")

# Load data ---------------------------------------------------------------

load("temp/data_for_analysis_donors.RData")
load("temp/data_for_analysis_public.RData")


# Specify parameters ------------------------------------------------------

parameters <- list(list(), list(), list())

w_race <- c(0.6, 0.2, 0.2)

# Selection of baselines

parameters <- specify_parameters(df_cleaned_donors, "Gender", "Male", 1)
parameters <- specify_parameters(df_cleaned_donors, "Race", "White", 0, w_race)
parameters <- specify_parameters(df_cleaned_donors, "Partisanship", "Republican", 1)
parameters <- specify_parameters(df_cleaned_donors, "Taxes", "Less progressive", 1) 
parameters <- specify_parameters(df_cleaned_donors, "Discrimination", "Not a big problem", 1)
parameters <- specify_parameters(df_cleaned_donors, "Courts", "Obey courts", 1) 
parameters <- specify_parameters(df_cleaned_donors, "Investigations", "Independent", 1)
parameters <- specify_parameters(df_cleaned_donors, "Compromise", "Supports compromise", 1) 
parameters <- specify_parameters(df_cleaned_donors, "Voting", "Opposes voter ID laws", 1)

constraint_list <- list()

# Create model 

model <- formula(selected ~ 
                   `Gender` +
                   `Race` +
                   `Partisanship` +
                   `Taxes` +
                   `Discrimination` +
                   `Courts` +
                   `Investigations` + 
                   `Compromise` +
                   `Voting`)

# Set the order of attributes and levels ----------------------------------

Attribute_order <- c("Gender",
                     "Race",
                     "Partisanship",
                     "Taxes",
                     "Discrimination",
                     "Courts",
                     "Investigations",
                     "Compromise",
                     "Voting")

Level_order <- c(c("Male",
                   "Female"),
                 c("White",
                   "Black",
                   "Hispanic"),
                 c("Republican",
                   "Democrat"),
                 c("Less progressive",
                   "More progressive"),
                 c("Not a big problem",
                   "Prevent discrimination"),
                 c("Obey courts",
                   "Disregard politicized decisions"),
                 c("Independent", 
                   "Partisan involvement"),
                 c("Supports compromise", 
                   "Stand up to other party"),
                 c("Opposes voter ID laws", 
                   "Supports voter ID laws"))


# Estimate AMCEs ----------------------------------------------------------

df <- df_cleaned_donors

# Set color palette

default_colour_palette <- estimate_AMCEs("AMCEs_donors", df_cleaned_donors, model) %>%
  specify_color_palette(length(Attribute_order))

# Main results using all respondents

all.donor <- estimate_AMCEs("AMCEs (Donors, March 2019)", df_cleaned_donors, model)
plot_AMCEs("AMCEs (donors)", all.donor, width = 10, height = 12)
all.public <- estimate_AMCEs("AMCEs (Public, March 2019)", df_cleaned_public, model, weights = TRUE)
plot_AMCEs("AMCEs (public)", all.public, width = 10, height = 12)

# Subgroup analyses -------------------------------------------------------

republican.donor <- df_cleaned_donors %>%
  filter(partisanship_dum == 1) 
democrat.donor <- df_cleaned_donors %>%
  filter(partisanship_dum == 2) 
republican.public <- df_cleaned_public %>%
  filter(partisanship_dum_7 == 1)
democrat.public <- df_cleaned_public %>%
  filter(partisanship_dum_7 == 2)

republican.donor <- estimate_AMCEs("AMCEs, Republican (Donors, March 2019)", republican.donor, model) %>% mutate(Subgroup = "Donors, Republican")
democrat.donor <- estimate_AMCEs("AMCEs, Democrat (Donors, March 2019)", democrat.donor, model) %>% mutate(Subgroup = "Donors, Democrat")
republican.public <- estimate_AMCEs("AMCEs, Republican (Public, March 2019)", republican.public, model, weights = TRUE) %>% mutate(Subgroup = "Public, Republican")
democrat.public <- estimate_AMCEs("AMCEs, Democrat (Public, March 2019)", democrat.public, model, weights = TRUE) %>% mutate(Subgroup = "Public, Democrat")

all.4 <- bind_rows(democrat.donor, democrat.public, republican.donor, republican.public)

var_names <- all.4 %>% select(order, var.names) %>% group_by(order, var.names) %>% distinct() %>% ungroup() %>% select(-order)
var_names <- pull(var_names, var.names)

order <- all.4 %>% select(order) %>% distinct()
order <- pull(order, order)

g <- ggplot(all.4) +
  geom_hline(yintercept = 0, 
             size = .5, 
             colour = "darkgrey", 
             linetype = "solid") +
  geom_pointrange(aes(x = order,
                      y = Estimate,
                      ymin = lower,
                      ymax = upper, 
                      shape = Subgroup, 
                      color = Subgroup), 
                  position = position_dodge(width = 1),
                  size = 0.75, 
                  fatten = 3,
                  na.rm = TRUE,
                  show.legend = FALSE) +
  coord_flip(ylim = c(-0.5, 0.5)) +
  scale_y_continuous(breaks = seq(-0.4, 0.4, 0.2),
                     labels = c("-40%", "-20%", "0%", "20%", "40%")) +
  ylab("Average Marginal Component Effect") +
  theme_few(base_size = 16, 
            #base_family = ""
  ) +
  theme(plot.title = element_text(size = 18, colour = "black"),
        axis.text.x =  element_text(size = 16, colour = "black", hjust = .5 , vjust = 1),
        axis.text.y =  element_text(size = 16, colour = "black", hjust = 0  , vjust = 0),
        axis.ticks =   element_blank(),
        panel.grid.major.x =   element_line(colour = "grey50"),
        axis.title.y = element_text(size = 16, angle = 90, vjust = .01, hjust = .1),
        strip.text.x = element_text(size = 16, margin = margin(b = 5)),
        legend.text = element_text(size = 14),
        panel.border = element_blank(),
        legend.position = "bottom",
        legend.title = element_blank()) +
  scale_x_continuous(name = NULL,
                     breaks = order,
                     labels = var_names) +
  scale_shape_manual(values = c(17, 17, 15, 15)) +
  scale_color_manual(values = c("dodgerblue4", "firebrick4", "dodgerblue", "firebrick1")) + 
  guides(colour = guide_legend(nrow = 2))

g

ggsave(paste0("figures/all_four_comparison.pdf"), 
       plot = g, width = 12, height = 10)
